#include "StdAfx.h"
#include ".\pubtcpclient.h"

CPubTcpClient::CPubTcpClient(void)
{
	m_sckClient = INVALID_SOCKET;
}

CPubTcpClient::~CPubTcpClient(void)
{
	Close( );
}

int CPubTcpClient::Close( )
{
	if( m_sckClient != INVALID_SOCKET )
	{
		closesocket( m_sckClient );	
		m_sckClient = INVALID_SOCKET;
	}

	return TRUE;
}

int CPubTcpClient::Write( const char* buf, int len )
{
	int nResult = 0;
	if( IsOpen() )
		nResult = send( m_sckClient, buf,  len , 0 );

	return nResult;
}

int CPubTcpClient::Read( char* buf, int len  )
{
	int nResult = 0;
	if( IsOpen() )
		nResult = recv( m_sckClient, buf, len , 0 );

	return nResult;
}

int CPubTcpClient::Conn( const ULONG ip, u_short port )
{
	BYTE ips[4] = {0};
	char szHost[32] = {0};

	memcpy( ips, &ip, 4 );
	sprintf( szHost, "%d.%d.%d.%d", ips[0], ips[1], ips[2], ips[3] );

	return Conn( szHost, port );
}

int CPubTcpClient::Conn( const char* host, u_short port )
{	
	sockaddr_in  addr = {0};
	addr.sin_family = AF_INET;
	addr.sin_port = htons( port );
	addr.sin_addr.S_un.S_addr = inet_addr( host );

	m_sckClient  = socket( AF_INET, SOCK_STREAM, 0 );
	if( INVALID_SOCKET  == m_sckClient )
		return FALSE;

	int nErrCode = 0;
	int nResult = connect( m_sckClient, (const struct sockaddr*)&addr, sizeof(addr) );
	if( nResult != 0 )
	{
		nErrCode = WSAGetLastError( );
		Close( );
		return FALSE;
	}

	return TRUE;
}

int CPubTcpClient::IsOpen(void)
{
	if( m_sckClient == INVALID_SOCKET )
		return FALSE;
	else
		return TRUE;

	return FALSE;
}

int CPubTcpClient::IsReadable( int timeout )
{
	return IsSocketReadable( m_sckClient, timeout );

	return TRUE;
}
